<script setup lang="ts">
import request from '@/utils/request'
import { onMounted, ref } from 'vue'
import 'nprogress/nprogress.css'
import { log } from 'console'

let viewToken = ''
let viewer3D
let app
let extObjMng = null
let extObjId = null
let BimModel

const getToken = async () => {
  try {
    const res = await request({
      url: '/oauth2/token'
    })
    sessionStorage.setItem('accessToken', (res as { token: string }).token)
  } catch (error) {
    console.error(error)
  }
}

const getViewToken = async () => {
  try {
    const res = await request({
      url: '/view/token?fileId=10000862250862',
      method: 'get'
    })
    viewToken = res as string
    console.log(viewToken, 'viewToken')
  } catch (error) {
    console.error(error)
  }
}

const successCallback = (viewMetaData) => {
  let domShow = document.getElementById('domId')
  let webAppConfig = new Glodon.Bimface.Application.WebApplication3DConfig()
  webAppConfig.domElement = domShow
  app = new Glodon.Bimface.Application.WebApplication3D(webAppConfig)
  app.addView(viewToken)
  viewer3D = app.getViewer()
  viewer3D.addEventListener(Glodon.Bimface.Viewer.Viewer3DEvent.MouseClicked, (data) => {
    console.log(data, 'MouseClicked')
    elementId = data.elementId
  })

  viewer3D.addEventListener(Glodon.Bimface.Viewer.Viewer3DEvent.ModelAdded, function (data) {
    if (data == '10000857909577') {
      // 模型加载完成后进行位置调整
      // viewer3D.getModel('10000857909577').setModelTranslation({ x: 50, y: 10, z: 0 })
    }
    // 渲染3D模型
    viewer3D.render()
  })
}
const failureCallback = (error) => {
  console.error(error)
}

const initModel = () => {
  let loaderConfig = new BimfaceSDKLoaderConfig()
  loaderConfig.viewToken = viewToken
  BimfaceSDKLoader.load(loaderConfig, successCallback, failureCallback)
}

const addModel = () => {
  viewer3D.addView('5939af04dcd04d95aa64691687f87d40')
}

const addExternalObject = (idName, x) => {
  if (!extObjMng) {
    extObjMng = new Glodon.Bimface.Plugins.ExternalObject.ExternalObjectManager(viewer3D)
  }
  let objUrl =
    'https://static.bimface.com/attach/6db9d5bcf88640f997b23be61e870ee8_%E6%B1%BD%E8%BD%A6.3DS'
  // 将3DS对象添加为外部构件
  extObjMng.loadObject({ name: idName, url: { objectUrl: objUrl } }, function () {
    extObjId = extObjMng.getObjectIdByName(idName)
    console.log(extObjId, 'extObjId')

    // 对构件进行缩放
    extObjMng.scale(extObjId, {
      x: 0.001,
      y: 0.001,
      z: 0.001
    })
    // 将构件移至初始位置
    extObjMng.translate(extObjId, {
      x: x,
      y: -35.1,
      z: -0.15
    })
    viewer3D.render()
  })
}

const getArea = () => {
  viewer3D.getAreas(
    function (r) {
      console.log(r)
    },
    function (e) {
      console.error(e)
    }
  )
}

const getIds = () => {
  if (!extObjMng) return false
  const arr = extObjMng.getAllObjectIds()
  console.log(arr)
  const modelData = extObjMng.getBoundingBoxById(arr[0])
  console.log(modelData)
  console.log(extObjMng, 'extObjMng')

  const objectData = extObjMng.getObjectData(arr[0])
  console.log(objectData, 'objectData')
  const objectDatatt = extObjMng.getTransformation(arr[0])
  console.log(objectDatatt, 'objectDatatt')
}

let isIsolationActivated = false
function isolateComponents() {
  if (!isIsolationActivated) {
    // 设置隔离选项，指定其他构件为半透明状态
    let makeOthersTranslucent = Glodon.Bimface.Viewer.IsolateOption.MakeOthersTranslucent
    // 调用viewer3D.method，隔离楼层为"F2"的构件
    viewer3D.getModel().isolateComponentsByObjectData([{ levelName: 'F2' }], makeOthersTranslucent)
    // 渲染三维模型
    viewer3D.render()
    // 修改按钮的文字内容
    setButtonText('btnIsolation', '取消隔离')
  } else {
    // 清除隔离
    viewer3D.getModel().clearIsolation()
    // 渲染三维模型
    viewer3D.render()
    // 修改按钮的文字内容
    setButtonText('btnIsolation', '构件隔离')
  }
  isIsolationActivated = !isIsolationActivated
}

let elementId = ''

// ************************** 定位 **************************
let isZoomToSelectionActivated = false
function zoomToSelectedComponents() {
  if (!isZoomToSelectionActivated) {
    // 选中id为"271431"的构件
    viewer3D.getModel().addSelectedComponentsById(['271431'])
    // 定位到选中的构件
    viewer3D.getModel().zoomToSelectedComponents()
    // 清除构件选中状态
    viewer3D.getModel().clearSelectedComponents()
    setButtonText('btnZoomToSelection', '回到主视角')
  } else {
    // 切换至主视角
    viewer3D.setView(Glodon.Bimface.Viewer.ViewOption.Home)
    setButtonText('btnZoomToSelection', '构件定位')
  }
  isZoomToSelectionActivated = !isZoomToSelectionActivated
}

// ************************** 着色 **************************
let isOverrideActivated = false
function overrideComponents() {
  if (!isOverrideActivated) {
    // 新建color对象，指定关注构件被染色的数值
    let color = new Glodon.Web.Graphics.Color('#ffffff', 0.5)
    // 对关注构件进行着色

    viewer3D.overrideComponentsColorById([elementId], color)
    viewer3D.render()
    setButtonText('btnOverrideColor', '清除着色')
  } else {
    // 清除构件着色
    viewer3D.getModel().clearOverrideColorComponents()
    viewer3D.render()
    setButtonText('btnOverrideColor', '构件着色')
  }
  isOverrideActivated = !isOverrideActivated
}

// ************************** 按钮文字 **************************
function setButtonText(btnId, text) {
  let dom = document.getElementById(btnId)
  if (dom != null && dom.nodeName == 'BUTTON') {
    dom.innerText = text
  }
}

function getComponentProperty() {
  const res = viewer3D.getAllModels()
  console.log(res, 'res-all')
  viewer3D.getModel().getComponentProperty('140056', function (objectdata) {
    console.log('140056', JSON.stringify(objectdata))
  })
  ;['140056'].forEach((item) => {
    console.log(item)

    viewer3D.getModel().getComponentProperty(item, function (objectdata) {
      console.log(item, JSON.stringify(objectdata))
    })
  })
}

const scale = ref<number>(1)
const toScale = () => {
  if (extObjMng) {
    extObjMng && extObjMng.scale(elementId, { x: scale.value, y: scale.value, z: scale.value })
  } else {
    console.log('没有')
  }
}

const toColor = () => {
  extObjMng &&
    extObjMng.overrideColor({ ids: [elementId] }, new Glodon.Web.Graphics.Color('#ff0000', 1))
}
const toRemove = () => {
  extObjMng && extObjMng.removeById([elementId])
}

const toSet = () => {
  extObjMng &&
    extObjMng.setObjectData(elementId, [
      { a: 'bb', b: 'cc' },
      { a1: 'bb1', b1: 'cc1' }
    ])
}

const toOpen = () => {
  // 设置外部构件编辑器工具条的配置项
  let toolbarConfig = new Glodon.Bimface.Plugins.ExternalObject.ExternalObjectEditorToolbarConfig()
  toolbarConfig.viewer = viewer3D
  toolbarConfig.id = extObjMng.getObjectIdByName('a1')
  // 创建外部构件编辑器工具条
  let editor = new Glodon.Bimface.Plugins.ExternalObject.ExternalObjectEditorToolbar(toolbarConfig)
  // 显示编辑工具条
  editor.show()
  editor.addEventListener(
    Glodon.Bimface.Plugins.ExternalObject.ExternalObjectEditorToolbarEvent.EditingModeChanged,
    function (data) {
      console.log(data, '监听的')
    }
  )
}

let state
function getCurrentState() {
  // 保存当前模型浏览状态
  state = viewer3D.getCurrentState()
}

function setState() {
  if (state != null) {
    // 恢复模型浏览状态
    viewer3D.setState(state)
    viewer3D.render()
  } else {
    window.alert('请先保存一个模型浏览状态！')
  }
}

const getr = () => {
  const res = extObjMng.getTransformation(elementId)
  console.log(res)
}
const setr = () => {
  const arr = [
    0.000288, -0.001326, -0, 0, 0.000694, 0.000151, 0.000704, 0, -0.000688, -0.000149, 0.00071, 0,
    14.051, 22.056, 10.969, 1
  ]
  extObjMng.setTransformation(elementId, arr)
}

onMounted(async () => {
  const token = sessionStorage.getItem('accessToken')
  if (!token) {
    await getToken()
  }
  await getViewToken()
  initModel()
})
</script>

<template>
  <div class="wrapper">
    <div id="domId" style="width: 800px; height: 600px"></div>
    <button @click="addModel">添加模型</button>
    <button @click="addExternalObject('a1', 15)">添加外部构建</button>
    <button @click="addExternalObject('a2', 10)">添加外部构建2</button>
    <button @click="getArea">获取空间</button>
    <button @click="getIds">获取Id</button>

    <button class="button" id="btnIsolation" @click="isolateComponents()">构件隔离</button>
    <button class="button" id="btnZoomToSelection" @click="zoomToSelectedComponents()">
      构件定位
    </button>
    <button class="button" id="btnOverrideColor" @click="overrideComponents()">构件着色</button>
    <p>1</p>
    <button @click="getComponentProperty()">获取所有模型</button>
    <input type="text" v-model.number="scale" />
    <button @click="toScale()">缩放</button>
    <button @click="toColor()">上色</button>
    <button @click="toRemove()">移除</button>
    <button @click="toSet()">设置自定义属性</button>
    <button @click="toOpen()">打开编辑器</button>
    <button @click="getCurrentState()">保存状态</button>
    <button @click="setState()">恢复状态</button>
    <button @click="getr">获取</button>
    <button @click="setr">设置</button>
  </div>
</template>

<style scoped>
.wrapper {
  width: 1200px;
  height: 800px;
  border: 1px solid #000;
}
</style>
